﻿#region Dont Look This

// /*************************************************************************************
//
// * 文件名称：  MyOPCHelper.cs
//
// * 作       者：  jieaido@outlook.com
//
// * 创建日期：  2020/04/02/20:23
//
// * 修改日期:     2020/04/06/20:23
//
// * 功能描述：
//
//
//
//                               Copyright (c) Jieaido. AllRights Reserved
//
// *************************************************************************************/

#endregion Dont Look This

using HelpLibrary.OPCHelper;
using OPCAutomation;
using System;

namespace HelpLibrary.OPC
{
    public class MyOPCHelper
    {
        public OPCServer RSserver { get; set; }
        private static MyOPCHelper _current;
        private int itmHandleServer;
        private OPCGroup RSGroup; //组
        private OPCGroups RSGroups; //群组
        private OPCItems RSItems; //标签集合
        // public static Dictionary<int, string> OPCTagDicts = new Dictionary<int, string>();

        private MyOPCHelper()
        {
            RSserver = new OPCServer();
        }

        public static MyOPCHelper Instance
        {
            get
            {
                if (_current == null) _current = new MyOPCHelper();
                return _current;
            }
        }

        public OPCItem AddItem(string itemtag)
        {
            return MyOPCItems.AddItem(RSItems, itemtag);
        }

        public OPCServerState Connect(string servername)
        {
            RSserver.Connect(servername);
            return OPCServerState.OPCRunning;
        }

        public void CreateOPCGroup(bool IsAsync = true)
        {
            RSGroups = RSserver.OPCGroups;
            RSGroup = RSGroups.Add("RSGroup");
            SetGroupProperty(IsAsync);
            RSGroup.DataChange += RSGroup_DataChange;
            //KepGroup.AsyncWriteComplete += new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(KepGroup_AsyncWriteComplete);
            RSItems = RSGroup.OPCItems;
        }

        public OPCServerState DefaultConnect()
        {
            var serlist = GetServerList();
            var name = serlist.GetValue(serlist.GetLowerBound(0));

            return Connect(name.ToString());
        }

        public Array GetServerList()
        {
            try
            {
                object list = RSserver.GetOPCServers("127.0.0.1");
                return (Array)list;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                //throw;
            }

            return null;
        }

        /// <summary>
        ///     释放所有资源
        /// </summary>
        public void ReleaseOPC()
        {
            if (RSGroups != null) RSGroups.RemoveAll();
            RSserver.Disconnect();
        }

        public void RemoveItem(string itemtag)
        {
            MyOPCItems.RemoveItem(RSItems, itemtag);
        }

        private void RSGroup_DataChange(int transactionid, int numitems, ref Array clienthandles, ref Array itemvalues,
            ref Array qualities, ref Array timestamps)
        {
            for (var i = 1; i <= numitems; i++)
            {
                var id = int.Parse(clienthandles.GetValue(i).ToString());
                var item = MyOPCItems.FindItem(id);
                //item.ItemTag = clienthandles.GetValue(i).ToString();//此为添加item时的标记
                item.ItemValue = itemvalues.GetValue(i).ToString();
                item.ItemQualities = qualities.GetValue(i).ToString();
                item.ItemTimestamps = timestamps.GetValue(i).ToString();

                //MyOPCItems.MyOPCItem.Add(item);
            }

            MyOPCItems.Bindlist = MyOPCItems.GenerateBindlist();

            //var ss = MyOPCItems.OPCTagDict;
        }

        private void SetGroupProperty(bool isAsync)
        {
            RSGroups.DefaultGroupIsActive = true; //激活组。
            RSGroups.DefaultGroupDeadband = 0; // 死区值，设为0时，服务器端该组内任何数据变化都通知组。
            RSGroups.DefaultGroupUpdateRate = 200; //默认组群的刷新频率为200ms
            RSGroup.UpdateRate = 1000; //刷新频率为1秒。
            RSGroup.IsSubscribed = isAsync; //使用订阅功能，即可以异步，默认false
        }
    }
}